package com.yuzhihao.writejvm.attributes.runtimeva;

import com.yuzhihao.writejvm.attributes.Attributes;
import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * RuntimeVisibleAnnotationsAttribute  和 RuntimeInvisibleAnnotations 结构是异一样的
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.16">RuntimeVisibleAnnotationsAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日13:48:08
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class RuntimeVisibleAnnotationsAttribute extends Attributes {

    protected int num_annotations_u2 = 2;

    protected int num_annotations;

    protected List<Annotation> annotations = new ArrayList<>();

    public RuntimeVisibleAnnotationsAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        this.setCi(ci);
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.num_annotations = Parse.byteToInt(this.num_annotations_u2, dis);

            int i = 0;
            while (i < this.num_annotations){
                Annotation annotation = new Annotation();
                annotation.parse(dis,ci);
                this.annotations.add(annotation);
                i++;
            }
        } catch (IOException e) {
            log.error(e);
        }
    }

    @Override
    public String print(String print) {
        StringBuilder builder = new StringBuilder();
        builder.append("RuntimeVisibleAnnotations").append(PrintFormat.COLON).append(System.lineSeparator());

        for (int i = 0; i < this.annotations.size(); i++) {
            Annotation annotation = this.annotations.get(i);
            builder.append(annotation.print(PrintFormat.MEMPTY,i));
        }

        return builder.toString();
    }

}
